<template>
    <div>
        <el-form :label-width="lw" ref="form" :model="value">
            <el-form-item 
            v-for="(item,key) in options" 
            :key="key" 
            :rules="item.rules"
            :prop="key"
            :label="showLabel?item.title:undefined"
            >
            <!-- 生成input框 -->
                <el-input
                 :maxlength="item.max"
                 :disabled="item.dis"
                 :placeholder="item.ph"
                 :type="item.type"
                 v-if="item.tag==='input'"
                 v-model="value[key]"
                ></el-input>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {deepClone} from "uti/common";
/**
 * 判断是否为数字
 */
const isNumber=(value)=>typeof value==='number';
    export default {
        name:"MyForm",
        mounted(){
            const {validate,clearValidate }=this.$refs.form;
            Object.assign(this,{validate,clearValidate});
        },
        computed: {
            /**
     * 处理后的表单配置
     */
    options() {
      const options = deepClone(this.opts);
      for (const key in options) {
        if (Object.hasOwnProperty.call(options, key)) {
          const item = options[key];
          item.tag = item.tag || "input";
          item.type = item.type || "text";
          item.rules = item.rules || [];

          if (item.required) {
            item.rules.unshift({ required: true });
          }

          for (const rule of item.rules) {
            if (rule.message) {
              continue;
            }
            if (rule.required) {
              rule.message = item.title + "不能为空";
            } else if (isNumber(rule.min) && isNumber(rule.max)) {
              rule.message = `${item.title}长度为${rule.min}到${rule.max}`;
            } else if (isNumber(rule.min)) {
              rule.message = `${item.title}的最小长度为${rule.min}`;
            } else if (isNumber(rule.max)) {
              rule.message = `${item.title}的最大长度为${rule.max}`;
            }
          }
        }
      }
      return options;
    },
        },
        props:{
            /**
             * 显示label
             */
            showLabel:{
               type:Boolean,
               default:true,
            },
            /**
             * label的宽度
             */
            lw:{
                type:String,
                default:"80px",
            },
             /**
             * 表单配置项
             */
            opts:{
                require:true,
                type:Object,
                default:()=>{},
            },
            /**
             * 绑定的值
             */
            value:{
                required:true,
                type:Object,
                default:()=>{},
            }
        }
    }
</script>

<style lang="scss" scoped>

</style>